# -*- coding: utf-8 -*-
"""
基于上下文管理器实现的selenium简单的登录获取cookie操作
"""
import json
from selenium import webdriver
from selenium.webdriver.chrome.options import Options


class Selenium:

    def __enter__(self):
        self.chrome_options = Options()
        self.chrome_options.add_argument('--headless')
        self.driver = webdriver.Chrome(options=self.chrome_options)  # 配置无头浏览器
        # self.driver = webdriver.Chrome()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.driver.close()

    def go_page(self, url):
        self.driver.get(url)

    def input(self, xpath, value):
        self.driver.find_element_by_css_selector(xpath).send_keys(value)

    def click(self, xpath):
        self.driver.find_element_by_css_selector(xpath).click()

    def get_cookie(self):
        cookies_list = self.driver.get_cookies()
        cookie = {}
        for item in cookies_list:
            cookie[item['name']] = item['value']
            self.save_cookie(cookie)

    def write_json(self, filapath):
        f = open(filapath, 'w')
        return f

    def save_cookie(self, cookie):
        wj = self.write_json('cookie')
        wj.write(json.dumps(cookie))

    def run(self):
        print('正在初始化浏览器')
        self.go_page(url)


if __name__ == '__main__':
    url = 'http://www.streffy.com/GTDX/Account/Login?ReturnUrl=%2FGTDX%2F#/storeList'
    with Selenium()as s:
        s.go_page(url=url)
        s.input('#LoginForm > div:nth-child(4) > div > input', 'admin')
        s.input('#LoginForm > div:nth-child(5) > div > input', '123qwe')
        s.click('#LoginButton')
        s.get_cookie()
        import time

        time.sleep(10)
